import { _decorator, Button, Component, director, Label, Node, Sprite, SpriteFrame, Toggle } from 'cc';
import { loadRes } from '../utils/loadRes';
import { gameConfig } from '../data/gameConfig';
import { nodePool } from '../utils/nodePool';
import { emits, localData } from '../data/enums';
const { ccclass, property } = _decorator;

@ccclass('txItem')
export class txItem extends Component {
    txNum: number = 0;
    jinbiNum: number = 0;
    isGet = 0;
    @property(Sprite)
    txSprite: Sprite = null;
    @property(Sprite)
    jinbiSprite: Sprite = null;
    @property(Sprite)
    isChicked: Sprite = null;
    @property(Node)
    selectSprite: Node = null;
    @property(Label)
    jinbiLabel: Label = null;
    @property(Toggle)
    txToggle: Toggle = null;
    @property(Button)
    buyBtn: Button = null;

    init() {
        this.txSprite.spriteFrame = loadRes.ins.getSpriteFrame(`animal${this.txNum}`);
        this.jinbiLabel.string = this.jinbiNum.toString();
        if (this.isGet == 1) {
            this.jinbiSprite.node.active = false;
            this.jinbiLabel.string = "已拥有";
            this.buyBtn.interactable = false;
            this.txToggle.interactable = true;
        } else {
            //没解锁的不触发单选
            this.buyBtn.interactable = true;
            this.txToggle.interactable = false;
            this.isChicked.node.active = false;
        }
        if(gameConfig.currTxNum != this.txNum){
            this.isChicked.node.active = false;
        }
    }
    clickBuy() {
        //判断金币是否足够
        if (gameConfig.jinbiNum >= this.jinbiNum) {
            gameConfig.jinbiNum -= this.jinbiNum;
            gameConfig.txList[this.txNum - 1].isGet = 1;
            this.isGet = 1;
            //存储购买信息
            localStorage.setItem(localData.playerTxList, JSON.stringify(gameConfig.txList));
            localStorage.setItem(localData.jinbiNum, gameConfig.jinbiNum.toString());
            director.emit(emits.jinbi);
            //弹出提示
            nodePool.ins.getPoolNode("toast", this.node.parent.parent);
            director.emit(emits.toast, "购买成功");
            this.init();
        } else {
            nodePool.ins.getPoolNode("toast", this.node.parent.parent);
            director.emit(emits.toast, "金币不足");
        }
    }
    clickSelect() {
        if (this.txNum == 0) return;

        console.log("aaa");
        console.log(this.txNum);
        if (this.isGet == 1) {
            gameConfig.currTxNum = this.txNum;
            localStorage.setItem(localData.curTx, gameConfig.currTxNum.toString());
            director.emit(emits.playerTx);
        }
    }
}


